package com.ai.zuochengyun.phase01.class03;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 按层遍历二叉树
 */
public class Code12_LevelTraversalBT {

    public static void main(String[] args) {
        BinaryTreeNode head = new BinaryTreeNode(1);
        head.left = new BinaryTreeNode(2);
        head.right = new BinaryTreeNode(3);
        head.left.left = new BinaryTreeNode(4);
        head.left.right = new BinaryTreeNode(5);
        head.right.left = new BinaryTreeNode(6);
        head.right.right = new BinaryTreeNode(7);
        process(head);
    }
    
    public static void process(BinaryTreeNode head) {
        // 边界处理
        if (head == null) {
            return;
        }

        Queue<BinaryTreeNode> queue = new LinkedList<>();
        // 队列满了add会抛出异常，而offer不会
        queue.add(head);
        while (!queue.isEmpty()) {
            BinaryTreeNode cur = queue.poll();
            System.out.println(cur.value);
            if (cur.left != null) {
                queue.add(cur.left);
            }
            if (cur.right != null) {
                queue.add(cur.right);
            }
        }
    }

}
